package com.shijun.im.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.shijun.im.R;
import com.shijun.im.activity.activity.RegistView;
import com.shijun.im.activity.interactor.RegistInteractor;
import com.shijun.im.activity.presenter.RegistPresenter;
import com.shijun.im.activity.presenter.impl.RegistPresenterImpl;
import com.shijun.im.utils.PopWindowUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhushijun on 2017/10/18 0018.
 */

public class RegistActivity extends AppCompatActivity implements RegistView, View.OnClickListener, View.OnFocusChangeListener {

    private ProgressBar progressBar;
    private EditText usernameEdit, passwordEdit, passwordCommitEdit, emailEdit, phoneEdit, addressEdit;
    private RegistPresenter presenter;
    private Button commitBut, concelBut;
    private ImageView avatarImg;
    private String avatarUrl;

    public static final int CODE_GALLERY_REQUEST = 100;
    public static final int CODE_CAMERA_REQUEST = 101;
    public static final int CODE_RESULT_REQUEST = 102;
    /* 头像文件 */

    public static final String IMAGE_FILE_PATH = "/DCIM/shijunIM/";
    public static final String IMAGE_TAKEPHOTO_TEMP_NAME = "temp_avatar.jpg";
    public static final String IMAGE_CROP_TEMP_NAME = "avatar.jpg";
    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    public static int output_X = 600;
    public static int output_Y = 600;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        progressBar = (ProgressBar) findViewById(R.id.activity_regist_main_progress_pro);
        usernameEdit = (EditText) findViewById(R.id.activity_regist_main_username_edit);
        passwordEdit = (EditText) findViewById(R.id.activity_regist_main_password_edit);
        passwordCommitEdit = (EditText) findViewById(R.id.activity_regist_main_password_commit_edit);
        emailEdit = (EditText) findViewById(R.id.activity_regist_main_email_edit);
        phoneEdit = (EditText) findViewById(R.id.activity_regist_main_phone_edit);
        addressEdit = (EditText) findViewById(R.id.activity_regist_main_address_edit);
        commitBut = (Button) findViewById(R.id.activity_regist_main_regist_commit_but);
        concelBut = (Button) findViewById(R.id.activity_regist_main_regist_concel_but);
        avatarImg = (ImageView) findViewById(R.id.activity_regist_main_avatar_img);

        presenter = new RegistPresenterImpl(this, this);

        commitBut.setOnClickListener(this);
        concelBut.setOnClickListener(this);
        avatarImg.setClickable(true);
        avatarImg.setOnClickListener(this);

        usernameEdit.setOnFocusChangeListener(this);
        passwordEdit.setOnFocusChangeListener(this);
        passwordCommitEdit.setOnFocusChangeListener(this);
        emailEdit.setOnFocusChangeListener(this);
        phoneEdit.setOnFocusChangeListener(this);
        addressEdit.setOnFocusChangeListener(this);

        try {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
            }
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void hideProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void showToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setInputError(final int key, final String content) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (key) {
                    case RegistInteractor.REGIST_USERNAMEERROR:
                        usernameEdit.setError(content);
                        break;
                    case RegistInteractor.REGIST_PASSWORDERROR:
                        passwordEdit.setError(content);
                        break;
                    case RegistInteractor.REGIST_PASSWORDCOMMITERROR:
                        passwordCommitEdit.setError(content);
                        break;
                    case RegistInteractor.REGIST_PHONEERROR:
                        phoneEdit.setError(content);
                        break;
                    case RegistInteractor.REGIST_EMAILERROR:
                        emailEdit.setError(content);
                        break;
                    case RegistInteractor.REGIST_ADDRESSERROR:
                        addressEdit.setError(content);
                        break;
                }
                commitBut.setBackgroundResource(R.drawable.button_red);

            }
        });
    }

    @Override
    public void setInputSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                commitBut.setBackgroundResource(R.drawable.button_blue);
            }
        });
    }

    @Override
    public void registSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegistActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    @Override
    public void registError() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("TAG", "注册失败！");
                Toast.makeText(RegistActivity.this, "注册失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void concelRegist() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
    }

    @Override
    public void setAvatar(final Bitmap bitmap) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                avatarImg.setImageBitmap(bitmap);
            }
        });
    }

    @Override
    public void openSelectAvatar() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                View viewPop = LayoutInflater.from(RegistActivity.this).inflate(R.layout.inflate_popwind_avatar_select, null);
                viewPop.findViewById(R.id.inflate_popwindow_avatar_select_location_but).setOnClickListener(RegistActivity.this);
                viewPop.findViewById(R.id.inflate_popwindow_avatar_select_cancel_but).setOnClickListener(RegistActivity.this);
                viewPop.findViewById(R.id.inflate_popwindow_avatar_select_takephoto_but).setOnClickListener(RegistActivity.this);
                PopWindowUtils.showPopupWindow(RegistActivity.this, viewPop, null, RegistActivity.this, true, Gravity.BOTTOM, 0, 0, 0.3f);
            }
        });
    }

    @Override
    public void closeSelectAvatar() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                PopWindowUtils.hidePopupWindow();
            }
        });
    }

    @Override
    public void onClick(View view) {
        presenter.onClick(view);
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                presenter.validateCredentials(getUserInfo());
            }
        });
    }

    private Map<String, String> getUserInfo() {
        Map<String, String> userinfo = new HashMap<String, String>();
        userinfo.put("username", usernameEdit.getText().toString().trim());
        userinfo.put("password", passwordEdit.getText().toString().trim());
        userinfo.put("passwordcommit", passwordCommitEdit.getText().toString().trim());
        userinfo.put("phone", phoneEdit.getText().toString().trim());
        userinfo.put("email", emailEdit.getText().toString().trim());
        userinfo.put("address", addressEdit.getText().toString().trim());
        userinfo.put("avatar", avatarUrl);
        return userinfo;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
        presenter.onActivityResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }
}
